package online.heycm.platform.common.tools.cipher.core;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;

/**
 * RSA非对称加密
 *
 * @author heycm
 * @since 2023/11/19 19:05
 */
public class RSACore {

    private RSACore() {
    }

    /**
     * 加密
     *
     * @param publicKey 公钥
     * @param content   内容
     * @return
     */
    public static String encrypt(String publicKey, String content) {
        RSA rsa = new RSA(null, publicKey);
        return encrypt(rsa, content);
    }

    /**
     * 加密
     *
     * @param rsa     RSA实例
     * @param content 内容
     * @return
     */
    public static String encrypt(RSA rsa, String content) {
        byte[] encrypt = rsa.encrypt(content, KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    /**
     * 解密
     *
     * @param privateKey 私钥
     * @param encrypt    密文
     * @return
     */
    public static String decrypt(String privateKey, String encrypt) {
        RSA rsa = new RSA(privateKey, null);
        return decrypt(rsa, encrypt);
    }

    /**
     * 解密
     *
     * @param rsa     RSA实例
     * @param encrypt 密文
     * @return
     */
    public static String decrypt(RSA rsa, String encrypt) {
        byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
        return StrUtil.str(decrypt, StandardCharsets.UTF_8);
    }

    /**
     * 生成秘钥对
     *
     * @return
     */
    public static KeyPair keyPair() {
        return SecureUtil.generateKeyPair("RSA");
    }

    /**
     * 生成秘钥对
     *
     * @return {私钥, 公钥}
     */
    public static String[] generateRSAKeys() {
        KeyPair keyPair = RSACore.keyPair();
        return new String[]{
                Base64.encode(keyPair.getPrivate().getEncoded()),
                Base64.encode(keyPair.getPublic().getEncoded())
        };
    }

    /**
     * 创建RSA实例
     *
     * @param privateKey 私钥
     * @param publicKey  公钥
     * @return
     */
    public static RSA rsa(String privateKey, String publicKey) {
        return new RSA(privateKey, publicKey);
    }
}
